package com.kevin.filter;

import java.io.IOException;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Set;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.springframework.security.web.util.AntPathRequestMatcher;
import org.springframework.security.web.util.RequestMatcher;

public class ViewFilter implements Filter {
	public static String fileName;
	private static String[] exclusionsArray;
	public static boolean reload;
	public static Properties prop;
	public static final String DEFAULT_FILENAME="view.properties";
	

	public void init(FilterConfig filterConfig) throws ServletException {
		fileName = filterConfig.getInitParameter("fileName");
		String exclusions = filterConfig.getInitParameter("exclusions");
		String _reload = filterConfig.getInitParameter("reload");
		if(fileName==null){
			fileName=DEFAULT_FILENAME;
		}
		if(exclusions==null){
			throw new ServletException("must specify exclusions");
		}
		if(_reload==null){
			_reload="false";
		}
		reload=Boolean.parseBoolean(_reload);
		exclusionsArray = StringUtils.split(exclusions, ",");
		loadProp();
	}
	
	public void loadProp(){
		prop=new Properties();
		try {
			prop.load(getClass().getClassLoader().getResourceAsStream(fileName));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
			FilterChain chain) throws IOException, ServletException {
		if(reload){
			loadProp();
		}
		HttpServletRequest request=(HttpServletRequest)servletRequest;
		boolean flag=false;
        if (exclusionsArray != null && exclusionsArray.length > 0) {
            for (String cacheURL : exclusionsArray) {
               RequestMatcher mather=new  AntPathRequestMatcher(cacheURL);
               if( mather.matches(request)){
                   flag = true;
                   break;
               }
            }
        }
        if(!flag){
        	Set<Entry<Object, Object>> entrySet = prop.entrySet();
        	for(Entry<Object, Object> entry:entrySet){
        		servletRequest.setAttribute(entry.getKey().toString(), entry.getValue());
        	}
        }
        chain.doFilter(servletRequest, servletResponse);
	}

	public void destroy() {
		
	}
}
